package cn.com.nes.site.module.dao.monitor;

import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.Page;
import cn.com.nes.common.util.UuidUtils;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public class TaskDaoImpl extends BaseDaoImpl {

    public PageData addControlTask(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("新增定时任务失败");
        Connection conn = null;
        Connection conn_ope = null;
        StringBuffer sb = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();
            conn_ope = DBUtils.getJdbcForOpe();
            List<String> sbids = (List<String>) req.getReqData().get("sbids");
            // 查询当前配置预警规则的设备是否为同一协议，不相同，不能进行预警规则保存
            sb.append("select  count(distinct c.protocol_id) from is_equipment_info a left join is_wxsb b on b.wx_id = a.wx_id left join is_device_protocol_info c on c.protocol_id = b.protocol_id where a.sb_id in (");
            for (int i = 0; i < sbids.size(); i++) {
                sb.append("'" + sbids.get(i) + "'");
                if (i < sbids.size() - 1) {
                    sb.append(",");
                }
            }
            sb.append(")");
            int protocolCount = this.queryForInt(conn_ope, sb.toString(), new Object[]{});
            if (protocolCount > 1) {
                res.setRetCode(9);
                res.setRetMessage("当前选中设备不是同一个协议，请选择相同协议的设备");
                return res;
            }

            String userId = req.getUinfo().getId();
            Date createTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(createTime) + " ";
            String taskId = (String) req.getReqData().get("uuid");
            String taskName = (String) req.getReqData().get("name");
            List<String> functionCodeList = (List<String>) req.getReqData().get("functionCodeList");
            List<String> functionNameList = (List<String>) req.getReqData().get("functionNameList");
            List<String> functionValueList = (List<String>) req.getReqData().get("functionValueList");
            List<String> startTimeList = (List<String>) req.getReqData().get("startTime");
            List<String> endTimeList = (List<String>) req.getReqData().get("endTime");
            List<String> fieldList = (List<String>) req.getReqData().get("fieldList") ;
            String timeType = String.valueOf(req.getReqData().get("timeType"));
            String webJson = (String) req.getReqData().get("webJson");
            String protocolId = (String) req.getReqData().get("protocolId");
            String areaCode = (String) req.getReqData().get("areaCode");
            String deviceType = (String) req.getReqData().get("deviceType");
            String deviceModel = (String) req.getReqData().get("deviceModel");

            if (StrUtil.isNotEmpty(taskId)) {
                sb.delete(0, sb.length());
                sb.append("update timer_task_control_detail set deleted = 1,modifyUid = ? where deleted = 0 and task_id=?");
                this.update(conn, sb.toString(), new Object[]{userId, taskId});
                sb.delete(0, sb.length());
                sb.append("update timer_task_control set name=?,timer_type=?,web_json=?,deleted=0,createUid=?,createTime=?,modifyUid=?,modifyTime=?,protocolId=?, deviceModel=?, deviceType=?, areaCode=?, company_id=? where task_id=?");
            } else {
                taskId = "task" + UuidUtils.generateUuid();
                sb.delete(0, sb.length());
                sb.append("insert into timer_task_control (name, timer_type, web_json, deleted, createUid, createTime, modifyUid, modifyTime, protocolId, deviceModel, deviceType, areaCode, company_id, task_id) values(?,?,?,0,?,?,?,?,?,?,?,?,?,?)");
            }

            this.update(conn, sb.toString(), new Object[]{taskName, timeType, webJson, userId, createTime, userId, createTime, protocolId, deviceModel, deviceType, areaCode, req.getUinfo().getCompanyId(), taskId});

            sb.delete(0, sb.length());
            sb.append("insert into timer_task_control_detail (task_id, sb_id, functionCode, functionName, functionValue, fieldName, startTime, endTime, deleted, createUid) values(?,?,?,?,?,?,?,?,?,?)");
            List<Object[]> list = new ArrayList<>();
            for (String sbid : sbids) {
                for (int i = 0; i < functionCodeList.size(); i++) {
                    list.add(new Object[]{taskId, sbid, functionCodeList.get(i), functionNameList.get(i), functionValueList.get(i), fieldList.get(i), dateStr + startTimeList.get(i), dateStr + endTimeList.get(i), 0, userId});
                }
            }
            this.updateBatch(conn, sb.toString(), list);

            res.setRetCode(0);
            res.setRetMessage("ok");
            conn.commit();
            conn_ope.commit();
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (conn_ope != null) {
                conn_ope.close();
            }
        }
        return res;
    }

    public PageData getControlTasks(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("查询定时任务失败");
        Connection conn = null;
        StringBuffer sb = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();

            String areaCode = (String) req.getReqData().get("areaCode");
            String deviceType = (String) req.getReqData().get("deviceType");
            String deviceModel = (String) req.getReqData().get("deviceModel");
            String protocolId = (String) req.getReqData().get("protocolId");
            String keywords = (String) req.getReqData().get("keywords");
            String companyId = req.getUinfo().getCompanyId();

            sb.append("select a.task_id, a.name, date_format(a.createTime, '%Y-%m-%d %T') as createTime, p.name as protocolName, GROUP_CONCAT(distinct b.sb_id) as sbids, " +
                    " GROUP_CONCAT(distinct substr(d.xzqh, 1, 2)) as xzqh, GROUP_CONCAT(distinct d.xzqh) as xzqhdm, GROUP_CONCAT(distinct t.xzqhmc) as xzqhmc, " +
                    " a.web_json, a.timer_type as timerType, s.sblx_id as deviceModel, s.sbxh as deviceModelName, v.dic_no as deviceType,v.title as deviceTypeName," +
                    " p.protocol_id as protocolId,GROUP_CONCAT(distinct b.fieldName) as fields," +
                    " a.areaCode as edit_areaCode, a.deviceType as edit_deviceType, a.deviceModel as edit_deviceModel, a.protocolId as edit_protocolId, " +
                    " count( distinct b.sb_id) as deviceCount \n" +
                    " from timer_task_control a\n" +
                    " inner join timer_task_control_detail b on a.task_id = b.task_id and b.deleted = 0\n" +
                    " inner join nes_ope_prod.is_equipment_info c on c.sb_id = b.sb_id and c.sfsc = 0\n" +
                    " inner join nes_ope_prod.is_install_info d on d.dd_id = c.dd_id and d.sfsc = 0\n" +
                    " inner join nes_ope_prod.t_xzqh t on t.xzqhdm like concat(substr(d.xzqh, 1, 2),'%') and t.xzqhjb = 1\n" +
                    " inner join nes_ope_prod.t_sblx s on s.sblx_id = c.sblx_id\n" +
                    " inner join nes_ope_prod.is_dict_value_info v on v.dic_no = s.sblx and type_id = 'd_type_2'\n" +
                    " inner join nes_ope_prod.is_wxsb w on w.wx_id = c.wx_id\n" +
                    " inner join nes_ope_prod.is_device_protocol_info p on p.protocol_id = w.protocol_id and p.is_deleted = 0\n" +
                    " where a.deleted = 0");
            sb.append(StrUtil.isEmpty(protocolId) ? "" : " and p.protocol_id = '" + protocolId +"'");
            sb.append(StrUtil.isEmpty(areaCode) ? "" : " and t.xzqhdm = '" + areaCode +"'");
            sb.append(StrUtil.isEmpty(deviceType) ? "" : " and v.dic_no = '" + deviceType +"'");
            sb.append(StrUtil.isEmpty(deviceModel) ? "" : " and s.sbxh = '" + deviceModel +"'");
            sb.append(StrUtil.isEmpty(keywords) ? "" : " and (d.xmlxr like concat('%','" + keywords +"','%') or d.xmlxrdh like concat('%','" + keywords +"','%'))");
            sb.append(StrUtil.isEmpty(companyId) ? "" : " and a.company_id = '" + companyId +"'");
            sb.append(" group by a.task_id, p.protocol_id order by a.createTime desc");
            StringBuffer sbfrom = new StringBuffer();
            sbfrom.append(sb.toString()) ;
            int idx=sbfrom.indexOf(" from ") ;
            sbfrom.delete(0, idx);
            Page page = new Page(conn,sbfrom.toString(),req.getPageid(),req.getPagesize(),res,new Object[]{}) ;
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize()) ;
            List<Map<String, Object>> list = this.queryForList(conn,sb.toString(), new Object[]{});

            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return res;
    }

    public PageData deleteControlTask(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("删除定时任务失败");
        Connection conn = null;
        StringBuffer sb = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();

            List<String> taskIds = (List<String>) req.getReqData().get("ids");
            for (String taskId : taskIds) {
                // 删除预警主表
                sb.append("update timer_task_control set deleted = 1 where task_id=?");
                this.update(conn, sb.toString(), new Object[]{taskId});

                // 删除预警设备
                sb.delete(0, sb.length());
                sb.append("update timer_task_control_detail set deleted = 1 where task_id=?");
                this.update(conn, sb.toString(), new Object[]{taskId});
            }
            res.setRetCode(0);
            res.setRetMessage("ok");
            conn.commit();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return res;
    }

}
